package demo603;

import java.sql.*;

public class UserDao {

    public UserDao() {
        // 初始化数据库连接工具等操作（如有）
    }

    /**
     * 根据用户名和密码查找用户
     *
     * @param username 用户名
     * @param password 密码
     * @return 如果找到用户则返回 User 对象，否则返回 null
     */
    public User findUser(String username, String password) throws SQLException, ClassNotFoundException {
        String url = "jdbc:mysql://localhost:3306/test_db";
        String dbUsername = "root";
        String dbPassword = "123456";

        Class.forName("com.mysql.cj.jdbc.Driver");

        try (Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?")) {
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return new User(rs.getString("username"));
            }
        }
        return null;
    }

    // 注册新用户
    public boolean register(String username, String password) {
        String url = "jdbc:mysql://localhost:3306/test_db";
        String dbUsername = "root";
        String dbPassword = "123456";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
                 PreparedStatement stmt = conn.prepareStatement("INSERT INTO users (username, password) VALUES (?, ?)")) {
                stmt.setString(1, username);
                stmt.setString(2, password);
                int rowsAffected = stmt.executeUpdate();
                return rowsAffected > 0;
            }
        } catch (Exception e) {
            // 建议使用日志框架记录异常信息
            System.err.println("注册失败：" + e.getMessage());
            return false;
        }
    }
}
